App({
  globalData: {
    userInfo: null,
    baseUrl: 'http://localhost:8888', 
    token: ''
  },
  onLaunch() {
    // 检查本地存储的登录状态
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    if (token && userInfo) {
      this.globalData.token = token;
      this.globalData.userInfo = userInfo;
    }
    
    // 获取系统信息
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.systemInfo = res;
      }
    });
  },
  // 登录方法
  login(userInfo, callback) {
    const app = this;
    // 调用后端 API 获取 token
    this.request({
      url: '/rental/user/login',
      method: 'POST',
      data: userInfo
    }).then((res) => {
      if (res.code === 200) {
        console.log('登录成功，返回数据:', res);
        app.globalData.userInfo = userInfo;
        app.globalData.token = res.token;
        
        // 存储登录状态
        wx.setStorageSync('token', res.token);
        wx.setStorageSync('userInfo', userInfo);
        
        if (callback) {
          callback();
        }
      } else {
        console.error('登录失败，错误码:', res.code, '错误信息:', res.message);
      }
    }).catch((err) => {
      console.error('登录请求出错:', err);
    });
  },
  // 检查是否登录
  checkLogin() {
    return !!this.globalData.token;
  },
  // 退出登录
  logout() {
    this.globalData.userInfo = null;
    this.globalData.token = '';
    
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
  },
  // 通用的API请求方法
  request(options) {
    const { url, method, data, header } = options;
    
    // 统一添加token到请求头
    const requestHeader = {
      ...header,
      'Authorization': `Bearer ${this.globalData.token}`
    };
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.globalData.baseUrl + url,
        method: method || 'GET',
        data,
        header: requestHeader,
        timeout: 10000, // 添加请求超时时间，单位为毫秒
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else if (res.statusCode === 401) {
            // 统一处理未授权情况
            this.logout();
            wx.navigateTo({
              url: '/pages/login/login'
            });
            reject(new Error('未授权，请重新登录'));
          } else {
            reject(new Error(res.data.message || '请求失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }
});